#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文件夹路径设置组件
"""

from PyQt6.QtWidgets import (QWidget, QHBoxLayout, QVBoxLayout, QLabel, 
                             QLineEdit, QPushButton, QFrame, QFileDialog, QDialog,
                             QComboBox, QTextEdit, QGridLayout, QMessageBox, QDateEdit)
from PyQt6.QtCore import Qt, pyqtSignal, QDate
import time
import configparser
import os


class FolderSettingsWidget(QWidget):
    """文件夹路径设置组件"""
    
    # 信号定义
    add_order_clicked = pyqtSignal(dict)  # 添加订单信号，传递订单数据
    path_changed = pyqtSignal(str, str)  # 路径变化信号 (path, date)
    
    def __init__(self, customers_data=None):
        super().__init__()
        self.customers_data = customers_data or []
        self.config_file = "settings.ini"
        self.init_ui()
        self.load_saved_settings()
    
    def load_saved_settings(self):
        """加载保存的设置"""
        try:
            if not os.path.exists(self.config_file):
                return
            
            config = configparser.ConfigParser()
            config.read(self.config_file, encoding='utf-8')
            
            # 加载共享文件夹
            if config.has_option('Settings', 'shared_folder'):
                shared_folder = config.get('Settings', 'shared_folder')
                if shared_folder:
                    self.path_input.setText(shared_folder)
                    print(f"📁 已加载共享文件夹: {shared_folder}")
            
        except Exception as e:
            print(f"❌ 加载保存的设置失败: {e}")
    
    def save_current_settings(self):
        """保存当前设置"""
        try:
            config = configparser.ConfigParser()
            
            # 如果文件存在，先读取现有配置
            if os.path.exists(self.config_file):
                config.read(self.config_file, encoding='utf-8')
            
            # 确保Settings节存在
            if not config.has_section('Settings'):
                config.add_section('Settings')
            
            # 保存当前值（只保存共享文件夹）
            shared_folder = self.path_input.text().strip()
            
            config.set('Settings', 'shared_folder', shared_folder)
            
            # 写入文件
            with open(self.config_file, 'w', encoding='utf-8') as f:
                config.write(f)
            
            print(f"💾 已保存设置: 文件夹={shared_folder}")
            
        except Exception as e:
            print(f"❌ 保存设置失败: {e}")
    
    
    def _auto_save_settings(self):
        """自动保存设置（延迟保存，避免频繁写入）"""
        # 使用定时器延迟保存，避免用户输入时频繁写入文件
        if hasattr(self, '_save_timer'):
            self._save_timer.stop()
        
        from PyQt6.QtCore import QTimer
        self._save_timer = QTimer()
        self._save_timer.setSingleShot(True)
        self._save_timer.timeout.connect(self.save_current_settings)
        self._save_timer.start(1000)  # 1秒后保存
        
    def init_ui(self):
        """初始化用户界面"""
        layout = QHBoxLayout(self)
        layout.setSpacing(8)
        layout.setContentsMargins(9, 9, 9, 9)

        self.label = QLabel("共享目录:")
        self.label.setObjectName("section_title")
        layout.addWidget(self.label)
        
        # 共享文件夹名输入框
        self.path_input = QLineEdit()
        self.path_input.setObjectName("path_input")
        self.path_input.setPlaceholderText("请输入共享文件夹名 (如: exam)")
        self.path_input.textChanged.connect(self._on_path_changed)
        self.path_input.textChanged.connect(self._auto_save_settings)  # 添加自动保存
        layout.addWidget(self.path_input)
        
        # 添加订单按钮
        self.add_order_btn = QPushButton("添加订单")
        self.add_order_btn.setObjectName("add_order_btn")
        self.add_order_btn.clicked.connect(self._show_add_order_dialog)
        layout.addWidget(self.add_order_btn)
        
    def get_path(self):
        """获取路径（已废弃，保留用于兼容性）"""
        return ""
        
    def get_date(self):
        """获取日期（共享文件夹名）"""
        return self.path_input.text()
        
    def set_path(self, path):
        """设置路径（已废弃，保留用于兼容性）"""
        pass
        
    def set_date(self, date):
        """设置日期（共享文件夹名）"""
        self.path_input.setText(date)
        
    def get_full_path(self):
        """获取完整路径（需要外部提供IP地址）"""
        # 这个方法现在需要外部提供IP地址才能构建完整路径
        return self.path_input.text().strip()
        
    def _on_path_changed(self):
        """路径变化处理"""
        shared_folder = self.path_input.text().strip()
        # 不再发送IP地址，只发送共享文件夹名
        self.path_changed.emit("", shared_folder)
    
    def _show_add_order_dialog(self):
        """显示添加订单对话框"""
        # 获取现有订单数据（如果已设置）
        existing_orders = getattr(self, 'existing_orders', [])
        dialog = AddOrderDialog(self, self.customers_data, existing_orders)
        if dialog.exec() == QDialog.DialogCode.Accepted:
            order_data = dialog.get_order_data()
            self.add_order_clicked.emit(order_data)
    
    def update_customers_data(self, customers_data):
        """更新客户数据"""
        self.customers_data = customers_data
    
    def set_existing_orders(self, existing_orders):
        """设置现有订单数据，用于重复检查"""
        self.existing_orders = existing_orders or []


class AddOrderDialog(QDialog):
    """添加订单对话框"""
    
    def __init__(self, parent=None, customers_data=None, existing_orders=None):
        super().__init__(parent)
        self.customers_data = customers_data or []
        self.existing_orders = existing_orders or []  # 现有订单数据
        self.setWindowTitle("添加新订单")
        self.setModal(True)
        self.setFixedSize(500, 350)
        self.init_ui()
        
    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout(self)
        layout.setSpacing(15)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # 创建表单布局
        form_layout = QGridLayout()
        form_layout.setSpacing(10)
        
        # 第一行
        form_layout.addWidget(QLabel("开头:"), 0, 0)
        self.start_combo = QComboBox()
        self.start_combo.addItems(["1", "2", "3", "4", "5", "6"])
        self.start_combo.setCurrentText("1")
        form_layout.addWidget(self.start_combo, 0, 1)
        
        form_layout.addWidget(QLabel("客户名称:"), 0, 2)
        self.customer_combo = QComboBox()
        self.customer_combo.setEditable(True)
        self.customer_combo.setPlaceholderText("请选择或搜索客户")
        self._setup_customer_search()
        self._load_customers()
        form_layout.addWidget(self.customer_combo, 0, 3)
        
        # 第二行
        form_layout.addWidget(QLabel("优先等级:"), 1, 0)
        self.priority_combo = QComboBox()
        self.priority_combo.addItems(["低级", "中级", "高级"])
        self.priority_combo.setCurrentText("中级")
        form_layout.addWidget(self.priority_combo, 1, 1)

        form_layout.addWidget(QLabel("交货日期:"), 1, 2)
        self.delivery_date_edit = QDateEdit()
        self.delivery_date_edit.setCalendarPopup(True)
        self.delivery_date_edit.setDisplayFormat("yyyy-MM-dd")
        # 设置默认日期为今天
        self.delivery_date_edit.setDate(QDate.currentDate())
        form_layout.addWidget(self.delivery_date_edit, 1, 3)
        
        # 第三行
        form_layout.addWidget(QLabel("是否挂版:"), 2, 0)
        self.pending_combo = QComboBox()
        self.pending_combo.addItems(["是", "否"])
        self.pending_combo.setCurrentText("否")
        self.pending_combo.currentTextChanged.connect(self._on_pending_changed)
        form_layout.addWidget(self.pending_combo, 2, 1)
        
        form_layout.addWidget(QLabel("文件类型:"), 2, 2)
        self.file_type_combo = QComboBox()
        self.file_type_combo.addItems(["PDF", "CDR"])
        self.file_type_combo.setCurrentText("PDF")
        form_layout.addWidget(self.file_type_combo, 2, 3)
        
        # 第四行 - 颜色和进纸方向（只在挂版为"是"时显示）
        self.color_label = QLabel("颜色:")
        self.color_label.setVisible(False)  # 默认隐藏标签
        self.color_combo = QComboBox()
        self.color_combo.addItems(["", "单黑", "双色", "三色", "四色"])
        self.color_combo.setCurrentText("")  # 默认为空
        self.color_combo.setVisible(False)  # 默认隐藏
        
        self.direction_label = QLabel("进纸方向:")
        self.direction_label.setVisible(False)  # 默认隐藏标签
        self.direction_combo = QComboBox()
        self.direction_combo.addItems(["", "上下", "左右"])
        self.direction_combo.setCurrentText("")  # 默认为空
        self.direction_combo.setVisible(False)  # 默认隐藏
        
        form_layout.addWidget(self.color_label, 3, 0)
        form_layout.addWidget(self.color_combo, 3, 1)
        form_layout.addWidget(self.direction_label, 3, 2)
        form_layout.addWidget(self.direction_combo, 3, 3)
        
        # 第五行
        form_layout.addWidget(QLabel("接单人:"), 4, 0)
        self.order_taker_combo = QComboBox()
        self.order_taker_combo.addItems(["1号客服", "2号客服", "3号客服"])
        self.order_taker_combo.setCurrentText("1号客服")
        form_layout.addWidget(self.order_taker_combo, 4, 1)
        
        form_layout.addWidget(QLabel("设计人:"), 4, 2)
        self.designer_combo = QComboBox()
        self.designer_combo.addItems(["拼版1号", "拼版2号", "外发1号", "外发2号", "外发3号", "外发4号"])
        self.designer_combo.setCurrentText("拼版1号")
        form_layout.addWidget(self.designer_combo, 4, 3)
        
        layout.addLayout(form_layout)
        
        # 客户备注
        notes_label = QLabel("客户备注:")
        layout.addWidget(notes_label)
        
        self.notes_text = QTextEdit()
        self.notes_text.setPlaceholderText("请输入客户备注信息...")
        self.notes_text.setMaximumHeight(80)
        layout.addWidget(self.notes_text)

        layout.addStretch()
        
        # 按钮区域
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        cancel_btn = QPushButton("取消")
        cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(cancel_btn)
        
        confirm_btn = QPushButton("确认添加")
        confirm_btn.setObjectName("confirm_btn")
        confirm_btn.clicked.connect(self.accept)
        button_layout.addWidget(confirm_btn)
        
        layout.addLayout(button_layout)
    
    def _setup_customer_search(self):
        """设置客户搜索功能"""
        from PyQt6.QtWidgets import QCompleter
        from PyQt6.QtCore import Qt
        
        # 创建自动完成器
        self.customer_completer = QCompleter()
        self.customer_completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
        self.customer_completer.setFilterMode(Qt.MatchFlag.MatchContains)
        self.customer_completer.setCompletionMode(QCompleter.CompletionMode.PopupCompletion)
        
        # 设置到ComboBox
        self.customer_combo.setCompleter(self.customer_completer)
        
        # 连接文本变化信号
        self.customer_combo.editTextChanged.connect(self._on_customer_text_changed)
    
    def _on_customer_text_changed(self, text: str):
        """处理客户名称文本变化"""
        if not text:
            return
        
        # 过滤匹配的客户
        matching_customers = []
        for customer in self.customers_data:
            customer_name = customer.get('name', '')
            if text.lower() in customer_name.lower():
                matching_customers.append(customer_name)
        
        # 更新Completer的模型
        from PyQt6.QtCore import QStringListModel
        model = QStringListModel(matching_customers)
        self.customer_completer.setModel(model)
    
    def _load_customers(self):
        """加载客户数据到下拉框"""
        self.customer_combo.clear()
        
        if self.customers_data:
            # 从客户数据中加载客户名称
            customer_names = [customer.get('name', '') for customer in self.customers_data if customer.get('name')]
            self.customer_combo.addItems(customer_names)
            
            # 更新Completer的模型
            from PyQt6.QtCore import QStringListModel
            model = QStringListModel(customer_names)
            self.customer_completer.setModel(model)
            
            print(f"📋 加载了 {len(customer_names)} 个客户到订单对话框")
        else:
            print("📋 没有客户数据")
    
    def update_customers_data(self, customers_data):
        """更新客户数据并刷新下拉框"""
        self.customers_data = customers_data
        self._load_customers()
        
        # 如果当前有输入文本，重新过滤
        current_text = self.customer_combo.currentText()
        if current_text:
            self._on_customer_text_changed(current_text)
    
    def _on_pending_changed(self, text: str):
        """处理是否挂版选择变化"""
        is_pending = (text == "是")
        
        # 显示或隐藏颜色和进纸方向字段
        self.color_label.setVisible(is_pending)
        self.color_combo.setVisible(is_pending)
        self.direction_label.setVisible(is_pending)
        self.direction_combo.setVisible(is_pending)
        
        # 当挂版从"否"改为"是"时，清空颜色和进纸方向
        if is_pending:
            self.color_combo.setCurrentText('')
            self.direction_combo.setCurrentText('')
        
        # 调整对话框大小
        if is_pending:
            self.setFixedSize(500, 400)  # 增加高度以容纳新字段
        else:
            self.setFixedSize(500, 350)  # 恢复原始高度
    
    def accept(self):
        """重写accept方法，添加客户名称重复检查"""
        # 获取当前输入的客户名称
        customer_name = self.customer_combo.currentText().strip()
        
        if not customer_name:
            QMessageBox.warning(self, "输入错误", "请选择客户名称！")
            return
        
        # 检查是否与现有订单中的客户名称重复
        existing_customers = []
        for order in self.existing_orders:
            order_customer = order.get('customer', '').strip()
            if order_customer:
                existing_customers.append(order_customer)
        
        if customer_name in existing_customers:
            QMessageBox.warning(
                self, 
                "客户名称重复", 
                f"客户名称 '{customer_name}' 已存在于现有订单中，请选择其他客户！"
            )
            return
        
        # 如果没有重复，调用父类的accept方法
        super().accept()
        
    def get_order_data(self):
        """获取订单数据"""
        return {
            'start_number': self.start_combo.currentText(),  # 发送开头数字，让服务端生成编号
            'customer': self.customer_combo.currentText(),
            'is_completed': False,
            'not_engraved': False,
            'solid_state': False,
            'not_confirmed': False,
            'pending': False,
            'done': False,
            'priority': self.priority_combo.currentText(),
            'notes': self.notes_text.toPlainText(),
            'is_pending_engraving': self.pending_combo.currentText() == "是",
            'color': self.color_combo.currentText(),
            'paper_direction': self.direction_combo.currentText(),
            'file_type': self.file_type_combo.currentText(),
            'delivery_date': self.delivery_date_edit.date().toString("yyyy-MM-dd"),
            'order_taker': self.order_taker_combo.currentText(),
            'designer': self.designer_combo.currentText(),
            'proofreader': '',
            'proofreading_time': '',
            'path': '',  # 新订单暂时没有路径
            'is_selected': False
        }
